package com.zts.modules.sys.service.impl;

import com.google.common.base.Strings;
import com.zts.base.exception.*;
import com.zts.base.page.PageBound;
import com.zts.modules.sys.entity.Role;
import com.zts.modules.sys.entity.User;
import com.zts.modules.sys.entity.UserGroupRelation;
import com.zts.modules.sys.entity.UserGroups;
import com.zts.modules.sys.mapper.GroupMapper;
import com.zts.modules.sys.mapper.RoleMapper;
import com.zts.modules.sys.mapper.UserMapper;
import com.zts.modules.sys.service.GroupService;
import com.zts.modules.sys.service.UserService;
import com.zts.util.BeanUtil;
import com.zts.util.BeanValidatorsUtil;
import com.zts.util.EncodeClass;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * Created by Zhangkh on 2017/6/2.
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;

    @Autowired
    RoleMapper roleMapper;

    @Autowired
    GroupMapper groupMapper;

    @Autowired
    GroupService groupService;


    @Override
    public User get(Long id) {
        if (null == id || id < 0) {
            throw new InvalidArgumentException("参数<id>为空");
        }

        User user = userMapper.get(id);
        if (null == user) {
            throw new SourceNotFoundException("id[" + id + "]对应的用户不存在！");
        }

        user.setGroups(userMapper.getGroups(String.valueOf(id)));
        return user;
    }

    @Override
    public List<User> getByEntity(User entity) {
        return null;
    }

    @Override
    public List<User> getByCondition(Map<String, Object> conditions) {
        return null;
    }

    @Override
    public List<User> getList(User entity, PageBound pageBound) {
        if (null == entity) {
            entity = new User();
        }

        List<User> userList = userMapper.getList(entity, pageBound);
        //拼接 id 串。
        String userIds = "";
        for (User user : userList) {
            if (user.getId() != null && user.getId() > 0) {
                userIds = userIds + user.getId() + ",";
            }
        }

        userIds = userIds + 0;
        List<UserGroups> groupsList = userMapper.getGroups(userIds);

        userList.forEach(user -> {
            Long userId = user.getId();
            List<UserGroups> maps = groupsList.stream().filter(e -> e.getUserId().equals(userId)).collect(Collectors.toList());
            user.setGroups(maps);
        });
        return userList;
    }


    @Override
    @Transactional
    public int update(User user) {
        if (null == user || null == user.getId() || user.getId() <= 0) {
            throw new InvalidArgumentException("参数对象或参数<id>为空");
        }
        User old = userMapper.get(user.getId());
        if (null == old) {
            throw new SourceNotFoundException("id[" + user.getId() + "]对应的用户不存在！");
        }
        BeanUtils.copyProperties(user, old, BeanUtil.getNullPropertyNames(user));
        BeanValidatorsUtil.validateWithException(old);
        return userMapper.update(old);
    }

    @Override
    @Transactional
    public int delete(User user) {
        //用户id必须存在，否则抛出异常。
        if (null == user) {
            throw new InvalidArgumentException("对象不能为空");
        } else if (null == user.getId() || user.getId() <= 0) {
            throw new InvalidArgumentException("必须传入id ");
        }
        //数据库中是否存在相应用户
        User dbUser = userMapper.get(user.getId());
        if (null == dbUser) {
            throw new SourceNotFoundException("id[" + user.getId() + "]对应的用户不存在！");
        }
        return userMapper.delete(user);
    }

    @Override
    public User save(User entity) {
        return null;
    }

    public User checkValid(String loginKey, String password) {
        if (Strings.isNullOrEmpty(loginKey) || Strings.isNullOrEmpty(password)) {
            throw new InvalidArgumentException("用户登录名(loginName)或者密码为空");
        }
        User user = userMapper.getByLoginKey(loginKey);
        if (user == null || Strings.isNullOrEmpty(user.getPassword())) {
            throw new SourceNotFoundException("用户不存在");
        }
        String enCodePassword = EncodeClass.enCode(user.getSalt(), password);
        if (!enCodePassword.equals(user.getPassword())) {
            throw new UnauthorizedException("密码校验失败！");
        }
        return user;
    }

    @Override
    @Transactional
    public User insert(User entity) {
        if (null == entity) {
            throw new InvalidArgumentException("参数不合法");
        }
        //先对entity进行校验
        BeanValidatorsUtil.validateWithException(entity);

        entity.setSalt(EncodeClass.getSalt32());
        if (Strings.isNullOrEmpty(entity.getPassword())) {
            //默认密码为 身份证后六位，如果身份证为空，则为888888
            String idCard = entity.getIdcard();
            if (Strings.isNullOrEmpty(idCard)) {
                idCard = "888888888";
            }
            entity.setPassword(EncodeClass.MD5(idCard.substring(idCard.length() - 6, idCard.length())));
        }
        entity.setPassword(EncodeClass.enCode(entity.getSalt(), entity.getPassword()));

        //校验通过后执行新增操作
        int i = userMapper.insert(entity);
        if (i <= 0 || entity.getId() == null) {
            throw new InternalServerErrorException("新增失败");
        }

        //TODO:groupType暂时默认 全职,sortNum默认0
        groupService.addUserIntoGroup(entity.getId(), entity.getGroupId(), "1",0);
        return userMapper.get(entity.getId());
    }


    public User getByLoginKey(String loginKey) {
        if (Strings.isNullOrEmpty(loginKey)) {
            throw new InvalidArgumentException("传入的参数loginKey为空！");
        }
        User user = userMapper.getByLoginKey(loginKey);
        if (user == null) {
            throw new SourceNotFoundException("未找到对应用户");
        }
        user.setGroups(userMapper.getGroups(String.valueOf(user.getId())));
        return user;
    }

    @Override
    public boolean checkStatus(User user) {
        if (null != user) {
            if (Strings.isNullOrEmpty(user.getStatus()) || !"1".equals(user.getStatus())) {
                throw new ValidateException("校验失败：用户状态不可用！");
            }
        } else {
            throw new SourceNotFoundException("用户不存在！");
        }
        return true;
    }

    @Override
    public boolean checkStatus(Long userId) {
        User user = get(userId);
        return checkStatus(user);
    }

    @Transactional
    public int updatePassword(User user, String oldPassword, String newPassword) {
        if (user == null || Strings.isNullOrEmpty(user.getPassword())) {
            throw new SourceNotFoundException("用户不存在。");
        }
        String encodePw = EncodeClass.enCode(user.getSalt(), oldPassword);
        if (!encodePw.equals(user.getPassword())) {
            throw new UnauthorizedException("旧密码错误");
        }
        //先校验未加密的密码
        user.setPassword(newPassword);
        BeanValidatorsUtil.validateWithException(user);

        String newEncodePw = EncodeClass.enCode(user.getSalt(), newPassword);
        user.setPassword(newEncodePw);
        return userMapper.updatePassword(user);
    }

    @Override
    public int updatePassword(Long id, String oldPassword, String newPassword) {
        if (id <= 0 || Strings.isNullOrEmpty(oldPassword) || Strings.isNullOrEmpty(newPassword)) {
            throw new InvalidArgumentException("旧密码或者新密码为空。");
        }
        User user = userMapper.get(id);
        return updatePassword(user, oldPassword, newPassword);
    }

    @Override
    public int updatePassword(String loginName, String oldPassword, String newPassword) {
        if (Strings.isNullOrEmpty(loginName) || Strings.isNullOrEmpty(oldPassword) || Strings.isNullOrEmpty(newPassword)) {
            throw new InvalidArgumentException("用户名、旧密码或者新密码为空。");
        }
        User user = userMapper.getByLoginKey(loginName);
        return updatePassword(user, oldPassword, newPassword);
    }

    @Override
    public List<Role> getUserRoles(Long userId) {
        if (userId <= 0) {
            throw new InvalidArgumentException("id参数不合法,必须大于零");
        }
        User user = userMapper.get(userId);
        if (user == null) {
            throw new SourceNotFoundException("用户不存在");
        }

        List<UserGroups> groupList = userMapper.getGroups(String.valueOf(userId));
        //用户必须加入到一个部门
        if (null == groupList || groupList.isEmpty()) {
            throw new ServiceException("用户未加入到部门");
        }
        //拼接 id 串。
        String groupIds = "";
        for (UserGroups u : groupList) {
            if (user.getId() != null && user.getId() > 0) {
                groupIds = groupIds + u.getGroupId() + ",";
            }
        }
        groupIds = groupIds + 0;

        // 先取用户所在部门的角色
        List<Role> groupRoles = roleMapper.getGroupRoles(groupIds);
        List<Role> userRoles = roleMapper.getUserRoles(userId);
        Set<Long> ids = new HashSet<>();
        for (Role r : userRoles) {
            ids.add(r.getId());
        }
        //去除重复的角色
        for (Role r : groupRoles) {
            if (ids.add(r.getId())) {
                userRoles.add(r);
            }
        }
        return userRoles;
    }

    public List<UserGroupRelation> getUserGroup() {
        return userMapper.getUserGroup();
    }

}
